//
//  WBUserAccountViewModel.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/7.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

class WBUserAccountViewModel: NSObject {

    
    // 单例全局访问点-> 目的使用数据共享
    static let sharedViewModel = WBUserAccountViewModel()
    
    private override init() {
        
        super.init()
        userAccount = WBUserAccount.loadUserAccount()
    }
    
    var userAccount: WBUserAccount?
    // 判断token的过期时间
    var accessToken: String? {
        
        guard let toke = userAccount?.access_token else {
            
            return nil
        }
        
        if userAccount?.expiresDate?.compare(Date()) == .orderedDescending {
            
            return toke
        } else {
            
            return nil
        }
    }
    // 通过token给isLogin
    var isLogin: Bool {
        
        return accessToken != nil
    }
    
    
    
    // 获取token
    func requestAccessToke(code: String,callBack:@escaping (Bool)->()) {
        
        WBNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil {
                
                print("网络请求异常:\(error!)")
                callBack(false)
                return
            }
            
            let dict = response as! [String:Any]
            let userAccount = WBUserAccount(dict: dict)
            
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
        }
        
    }
    // 获取用户信息
    func requestUserInfo(userAccount:WBUserAccount,callBack:@escaping (Bool)->()) {
        
        WBNetworkTools.sharedTools.requestUserInfo(token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            
            if error != nil {
                print("网络请求异常:\(error!)")
                callBack(false)
                return
            }
            
            let dic = response as! [String:Any]
            let name = dic["name"] as? String
            let avatar_large = dic["avatar_large"] as? String
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            // 保存用户数据
            userAccount.saveUserAccount()
            // MARK: --出现BUG点
            self.userAccount = userAccount
            callBack(true)
        }
        
    }

}
